const path = require('path')
const fs = require('fs')

// 登录需要的代理
const loginProxy = {
  '/iam/': { target: '', changeOrigin: true },
  '/auth/who': { target: '', changeOrigin: true },
}

module.exports = {
  resolve(rPath: any) {
    return path.join(__dirname, rPath)
  },
  getEnvInfo() {
    let envInfo = { env: '', envConf: {} }
    const file = this.resolve('./config/envInfo.js')
    if (fs.existsSync(file)) {
      delete require.cache[require.resolve(file)]
      envInfo = require(file)
    } else {
      console.error(`${file} 文件不存在，程序退出`)
      process.exit()
    }
    return envInfo
  },
  require(file: any) {
    delete require.cache[require.resolve(`${file}`)]
    return require(`${file}`)
  },
  getAllEnvProxy(_proxy: any) {
    const envInfo = this.getEnvInfo()
    const { envConf } = envInfo || {}
    const allProxy = {} as {
      [key: string]: any
    }
    const proxy = { ..._proxy, ...loginProxy }

    Object.entries(envConf).map(([env]) => {
      const { baseUrl } = envConf[env]
      Object.entries(proxy).map(([i]) => {
        const key = `/${env}${i}`
        allProxy[key] = {
          target: baseUrl,
          changeOrigin: true,
          secure: false,
          xfwd: false,
          rewrite: (path: string) =>path.replace(new RegExp(`^/${env}`), ''),
          configure: (proxy: {
              on: (arg0: string, arg1: (proxyReq: {
                setHeader: (arg0:
                  // 登录需要的代理
                  string, arg1: any) => void
              }, req: any, res: any) => void) => void
            }) => {
            proxy.on('proxyReq', (proxyReq: { setHeader: (arg0: string, arg1: any) => void }, req: any, res: any) => {
              const envInfo = this.getEnvInfo()
              const conf = envInfo.envConf[env]
              proxyReq.setHeader('tenantcode', conf.tenantId)
              proxyReq.setHeader('tenant-code', conf.tenantId)
              proxyReq.setHeader('tenantid', conf.tenantId)
              proxyReq.setHeader('content-type', 'application/json')
              proxyReq.setHeader('x-xsrf-token', conf['x-xsrf-token'])
              proxyReq.setHeader('cookie', conf.cookie)
            });
          },
        }
      })
    })
    return allProxy
  },
}
